package com.tech.connect.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.ksy.common.dialog.BaseDialog;
import com.ksy.common.dialog.ItemsDialog;
import com.ksy.common.dialog.NumChooseDialog;
import com.ksy.common.image.ImageLoader;
import com.ksy.common.image.ImagePickActivity;
import com.ksy.common.model.City;
import com.ksy.common.utils.LogTool;
import com.ksy.common.utils.NumUtils;
import com.ksy.common.utils.ParamsUtil;
import com.ksy.oss.OssClient;
import com.ksy.oss.OssResult;
import com.tech.connect.R;
import com.tech.connect.api.BaseEntityOb;
import com.tech.connect.api.UserHttp;
import com.tech.connect.api.UserInfo;
import com.tech.connect.model.ItemCatSub;
import com.tech.connect.util.CatUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EditUserInfoActivity extends BaseActivity {

    private ImageView ivCover;
    private ImageView ivHead;
    private TextView tvNickName;
    private TextView tvName;
    private TextView tvAge;
    private TextView tvSex;
    private TextView tvAddress;
    private TextView tvHeight;
    private TextView tvWeight;
    private TextView tvMarry;
    private TextView tvStudy;
    private TextView tvSign;
    private String nickName;
    private String realName;
    private int age;
    private String gender;
    private float height;
    private float weight;
    private String sign;
    private String cityCode;
    private String provinceCode;
    private String areaCode;
    private String marriage;
    private String study;
    private String imageUrl;
    private String imageBackUrl;

    @Override
    protected boolean isShowHeadBar() {
        return false;
    }

    @Override
    protected void initImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar
                .fitsSystemWindows(false)
                .keyboardEnable(true)
                .init();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_userinfo);
        initView();
        initData();
    }

    private void initView() {
        findViewById(R.id.ivBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        findViewById(R.id.ivSyn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEmpty(cityCode)) {
                    showToast("请选择地址");
                    return;
                }
                if (isEmpty(nickName)) {
                    showToast("请填写昵称");
                    return;
                }
                if (isEmpty(realName)) {
                    showToast("请填写姓名");
                    return;
                }
                if (age < 0) {
                    showToast("请选择年龄");
                    return;
                }
                List<ParamsUtil.ParamsTwo<OssClient.FileType, String>> twoList = new ArrayList<>();

                if (!isEmpty(imageUrl)) {
                    twoList.add(ParamsUtil.getInstance().create(OssClient.FileType.Image, imageUrl));

                }
                if (!isEmpty(imageBackUrl)) {
                    twoList.add(ParamsUtil.getInstance().create(OssClient.FileType.Image, imageBackUrl));
                }
                if (twoList.size() > 0) {
                    showDialog();
                    OssClient.getInstance().update(activity, twoList, new OssClient.UpdatesListener() {
                        @Override
                        public void onFinish(final boolean isSuccess, final List<OssResult> results, List<String> ossUrls) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Map<String, Object> map = new HashMap<>();
                                    LogTool.e(results);
                                    LogTool.e("imageUrl " + imageUrl);
                                    LogTool.e("imageBackUrl " + imageBackUrl);
                                    if (isSuccess) {
                                        for (OssResult result : results) {
                                            if (result.isSuccess) {
                                                if (isSame(imageUrl, result.srcUrl)) {
                                                    map.put("headImage", result.aliUrl);
                                                } else if (isSame(imageBackUrl, result.srcUrl)) {
                                                    map.put("backgroundImage", result.aliUrl);
                                                }
                                            }
                                        }
                                        update(map);
                                    } else {
                                        hideDialog();
                                        showToast("图片上传失败");
                                    }
                                }
                            });
                        }
                    });
                } else {
                    update(null);
                }

            }
        });
        ivCover = findViewById(R.id.ivCover);
        ivCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImagePickActivity.comeIn(activity, false, 6, 992);
            }
        });
        ivHead = findViewById(R.id.ivHead);
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImagePickActivity.comeIn(activity, false, 6, 991);
            }
        });
        tvNickName = findViewById(R.id.tvNickName);
        tvNickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditTextActivity.class);
                intent.putExtra("data", tvNickName.getText().toString().trim());
                jump2Activity(intent, 1);
            }
        });
        tvName = findViewById(R.id.tvName);
        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditTextActivity.class);
                intent.putExtra("data", tvName.getText().toString().trim());
                jump2Activity(intent, 2);
            }
        });
        tvAge = findViewById(R.id.tvAge);
        tvAge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NumChooseDialog numChooseDialog = new NumChooseDialog(activity);
                numChooseDialog.setOnClickListener(new NumChooseDialog.ClickListener() {
                    @Override
                    public void enter(BaseDialog dialog, int num) {
                        dialog.dismiss();
                        age = num;
                        tvAge.setText(String.valueOf(num) + "岁");
                    }
                });
                numChooseDialog.show();
            }
        });
        tvSex = findViewById(R.id.tvSex);
        tvSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<ItemCatSub> items = CatUtils.getInstance().getCatListByCode("gender");
                ItemsDialog<ItemCatSub> itemsDialog = new ItemsDialog<>(activity, items, new ItemsDialog.ItemChooseListener() {
                    @Override
                    public void choose(ItemsDialog dialog, int position) {
                        dialog.dismiss();
                        ItemCatSub itemCatSub = items.get(position);
                        tvSex.setText(itemCatSub.description);
                        gender = itemCatSub.value;

                    }
                });
                itemsDialog.show();
            }
        });
        tvAddress = findViewById(R.id.tvAddress);
        tvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(CityChooseActivity.class, 10001);
//                AreaChooseDialog areaChooseDialog = new AreaChooseDialog(activity);
//                areaChooseDialog.setOnClickListener(new AreaChooseDialog.ClickListener() {
//                    @Override
//                    public void enter(BaseDialog dialog, AreaChooseDialog.Area area, AreaChooseDialog.Area areaSub, AreaChooseDialog.Area areaSubSub) {
//                        if (area != null) {
//                            LogTool.e(area.name);
//
//                        }
//                        if (areaSub != null) {
//                            LogTool.e(areaSub.name);
//
//                        }
//                        if (areaSubSub != null) {
//                            LogTool.e(areaSubSub.name);
//                        }
//                    }
//                });
//                areaChooseDialog.show();
            }
        });
        tvHeight = findViewById(R.id.tvHeight);
        tvHeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditNumActivity.class);
                intent.putExtra("data", tvHeight.getText().toString().trim());
                jump2Activity(intent, 3);
            }
        });
        tvWeight = findViewById(R.id.tvWeight);
        tvWeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditNumActivity.class);
                intent.putExtra("data", tvWeight.getText().toString().trim());
                jump2Activity(intent, 4);
            }
        });
        tvMarry = findViewById(R.id.tvMarry);
        tvMarry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<ItemCatSub> items = CatUtils.getInstance().getCatListByCode("marriage");
                ItemsDialog<ItemCatSub> itemsDialog = new ItemsDialog<>(activity, items, new ItemsDialog.ItemChooseListener() {
                    @Override
                    public void choose(ItemsDialog dialog, int position) {
                        ItemCatSub itemCatSub = items.get(position);
                        dialog.dismiss();
                        tvMarry.setText(itemCatSub.description);
                        marriage = itemCatSub.value;

                    }
                });
                itemsDialog.show();
            }
        });
        tvStudy = findViewById(R.id.tvStudy);
        tvStudy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<ItemCatSub> items = CatUtils.getInstance().getCatListByCode("education");
                ItemsDialog<ItemCatSub> itemsDialog = new ItemsDialog<>(activity, items, new ItemsDialog.ItemChooseListener() {
                    @Override
                    public void choose(ItemsDialog dialog, int position) {
                        ItemCatSub itemCatSub = items.get(position);
                        dialog.dismiss();
                        tvStudy.setText(itemCatSub.description);
                        study = itemCatSub.value;

                    }
                });
                itemsDialog.show();
            }
        });
        tvSign = findViewById(R.id.tvSign);
        tvSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EditTextActivity.class);
                intent.putExtra("data", tvSign.getText().toString().trim());
                jump2Activity(intent, 5);
            }
        });

    }

    private void initData() {
        UserInfo userInfo = UserInfo.getUserInfo();
        nickName = userInfo.nickName;
        realName = userInfo.realName;
        age = userInfo.age;
        gender = String.valueOf(userInfo.gender);
        cityCode = userInfo.cityCode;
        provinceCode = userInfo.provinceCode;
        areaCode = userInfo.areaCode;
        height = userInfo.height;
        weight = userInfo.weight;
        marriage = String.valueOf(userInfo.marriage);
        sign = userInfo.sign;

        ImageLoader.getInstance().loadHead(activity, userInfo.headImage, ivHead);
        ImageLoader.getInstance().load(activity, userInfo.backgroundImage, ivCover);
        tvNickName.setText(userInfo.nickName);
        tvName.setText(userInfo.realName);
        tvAge.setText(String.valueOf(userInfo.age) + "岁");
        tvSex.setText(userInfo.genderName);

        String provinceName = userInfo.provinceName;
        String cityName = userInfo.cityName;
        StringBuilder addressInfo = new StringBuilder();
        if (isNotEmpty(provinceName)) {
            addressInfo.append(provinceName).append(" ");
        }
        if (isNotEmpty(cityName)) {
            addressInfo.append(cityName).append(" ");
        }
        tvAddress.setText(addressInfo.toString());
        tvHeight.setText(NumUtils.getScale2String(userInfo.height) + "cm");
        tvWeight.setText(NumUtils.getScale2String(userInfo.weight) + "kg");
        tvMarry.setText(userInfo.marriageName);
        tvStudy.setText(userInfo.educationName);
        tvSign.setText(userInfo.sign);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                String data = intent.getStringExtra("data");
                tvNickName.setText(data);
                nickName = data;
            } else if (requestCode == 2) {
                String data = intent.getStringExtra("data");
                tvName.setText(data);
                realName = data;
            } else if (requestCode == 3) {
                String data = intent.getStringExtra("data");
                try {
                    height = Float.parseFloat(data);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                tvHeight.setText(NumUtils.getScale2String(height) + "cm");
            } else if (requestCode == 4) {
                String data = intent.getStringExtra("data");
                try {
                    weight = Float.parseFloat(data);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                tvWeight.setText(NumUtils.getScale2String(weight) + "kg");
            } else if (requestCode == 5) {
                String data = intent.getStringExtra("data");
                sign = data;
                tvSign.setText(data);
            } else if (requestCode == 10001) {
                //城市切换
                Serializable data = intent.getSerializableExtra("data");
                if (data != null && data instanceof City) {
                    City selectCity = (City) data;
                    cityCode = String.valueOf(selectCity.id);
                    tvAddress.setText(selectCity.name);
                }
            } else if (requestCode == 991) {
                ArrayList<String> paths = intent.getStringArrayListExtra(ImagePickActivity.Data_selectImages);
                if (paths != null && !paths.isEmpty()) {
                    imageUrl = paths.get(0);
                    ImageLoader.getInstance().loadHead(activity, imageUrl, ivHead);
                }

            } else if (requestCode == 992) {
                ArrayList<String> paths = intent.getStringArrayListExtra(ImagePickActivity.Data_selectImages);
                if (paths != null && !paths.isEmpty()) {
                    imageBackUrl = paths.get(0);
                    ImageLoader.getInstance().load(activity, imageBackUrl, ivCover);
                }

            }
        }
    }

    private void update(Map<String, Object> fileMap) {
        Map<String, Object> map = UserHttp.getMap();
        if (fileMap != null) {
            map.putAll(fileMap);
        }
        map.put("nickName", nickName);
        map.put("realName", realName);
        map.put("age", age);
        map.put("gender", gender);
        map.put("provinceCode", provinceCode);
        map.put("cityCode", cityCode);
        map.put("areaCode", areaCode);
        map.put("height", height);
        map.put("weight", weight);
        map.put("marriage", marriage);
        map.put("educationId", study);
        map.put("sign", sign);
        UserHttp.updateUserInfo(map, new BaseEntityOb<UserInfo>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, UserInfo data, String msg) {
                hideDialog();
                showToast(msg);
                if (isSuccess) {
                    UserInfo.getUserInfo().setDataInfoByLogIn(data);
                    imageUrl = "";
                    imageBackUrl = "";
                    setResult(RESULT_OK);
                }
            }
        });
    }
}